package com.such.kit.calendar.period.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.such.kit.calendar.DateCalculate;
import com.such.kit.calendar.DatePeriodHelper;
import com.such.kit.calendar.period.DatePeriod;
import com.such.kit.datacast.CastCommons;
import com.such.kit.string.StringCommons;

public class TendayPeriod extends DatePeriod {

	private SimpleDateFormat daySfd = CastCommons.getSimpleDateFormat("dd");

	public DatePeriod add(int amount) throws ParseException {
		Date tempDate = super.date;
		for (int i = 0; i < amount; i++) {
			while (true) {
				tempDate = DateCalculate.add(tempDate, 1, DateCalculate.UNIT_DAY);
				int day = Integer.valueOf(this.daySfd.format(tempDate));
				int nextDay = Integer.valueOf(this.daySfd.format(DateCalculate.subtract(tempDate, 1, DateCalculate.UNIT_DAY)));
				if (day == 11 || day == 21 || nextDay == 1) {
					break;
				}
			}
		}
		return DatePeriodHelper.getInstance(DatePeriodHelper.FREQ_TENDAY, super.sfd.format(tempDate), super.format);
	}

	public DatePeriod subtract(int amount) throws ParseException {
		Date tempDate = super.date;
		for (int i = amount; i > 0; i--) {
			while (true) {
				tempDate = DateCalculate.subtract(tempDate, 1, DateCalculate.UNIT_DAY);
				int day = Integer.valueOf(this.daySfd.format(tempDate));
				int prevDay = Integer.valueOf(this.daySfd.format(DateCalculate.add(tempDate, 1, DateCalculate.UNIT_DAY)));
				if (day == 10 || day == 20 || prevDay == 1) {
					break;
				}
			}
		}
		return DatePeriodHelper.getInstance(DatePeriodHelper.FREQ_TENDAY, super.sfd.format(tempDate), super.format);
	}

	public String firstFreqDay() {
		int day = Integer.valueOf(this.daySfd.format(super.date));
		if (day < 11) {
			day = 1;
		} else if (day < 21) {
			day = 11;
		} else {
			day = 21;
		}
		String date = StringCommons.merger(super.calendar.get(Calendar.YEAR), "-", super.calendar.get(Calendar.MONTH) + 1, "-", day);
		try {
			date = super.sfd.format(super.baseSfd.parse(date));
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		return date;
	}

	public String lastFreqDay() {
		int day = Integer.valueOf(this.daySfd.format(super.date));
		if (day < 11) {
			day = 10;
		} else if (day < 21) {
			day = 20;
		} else {
			day = super.calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		}
		String date = StringCommons.merger(super.calendar.get(Calendar.YEAR), "-", super.calendar.get(Calendar.MONTH) + 1, "-", day);
		try {
			date = super.sfd.format(super.baseSfd.parse(date));
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		return date;
	}

}
